import os, time, socket

class TcpServer(object):
	def __init__(self,endpoint='0.0.0.0:2014', messagelength=8, endmessage='byebye', loopsleep=0.005):
		self.endpoint = endpoint
		self.messagelength = messagelength
		self.endmessage = endmessage
		self.loopsleep = loopsleep

		self.invalidcount = 0

	def listen(self,target):
		host = self.endpoint.split(':')[0]
		port = int(self.endpoint.split(':')[1])

		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		sock.bind((host,port))
		sock.listen(0)
		print 'tcpsrv begin listen on {0} ..'.format(self.endpoint)

		request, addr = sock.accept()
		print addr[0]+' connected, enter message loop.'

		while True:
			data = request.recv(self.messagelength)

			if not self.data_verify(data):
				#print 'false data: '+data

				if target and target.msg_invalid:
					target.msg_invalid(data)

				if data == '':
					self.invalidcount = self.invalidcount+1

				if self.invalidcount >= 10:
					print 'to many empty message, client may lost, server will shutdown.'
					request.close()
					sock.close()
					print 'server shutdown.'

				time.sleep(self.loopsleep)
				continue

			self.invalidcount = 0

			if self.end_verify(data):
				request.close()
				sock.close()
				#print 'bye bye'

				if target and target.msg_bye:
					target.msg_bye()

				break
			#print 'valid message: '+data

			if target and target.msg_execute:
				target.msg_execute(data)

			time.sleep(self.loopsleep)


	def data_verify(self,data):
		if len(data) != self.messagelength or not data.endswith('\0'):
			return False

		return True

	def end_verify(self,data):
		if data.startswith('byebye'):
			return True

		return False


